package com.sloth.rabbitmq;

import com.sloth.pojo.SeckillList;
import com.sloth.pojo.SeckillMessage;
import com.sloth.pojo.SeckillOrder;
import com.sloth.service.SeckillService;
import com.sloth.util.JsonUtil;
import com.sloth.util.ServerResponse;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate redisTemplate;




    /**
     * 下单操作
     * @param message
     */
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message){
        System.out.println("接收消息:"+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        int secId = seckillMessage.getSecId();
        int custId = seckillMessage.getCustId();
        int addressId = seckillMessage.getAddressId();

        // 判断库存
        SeckillList seckill = seckillService.getSeckill(secId);
        if (seckill.getSecStock()<1){
            return;
        }

        // 判断是否重复下单
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + custId + ":" + secId);
        if (seckillOrder != null) {
            return ;
        }

        // 下单
        seckillService.seckill(secId,custId,addressId);


    }
}
